from rich.live import Live
from rich.table import Table
from rich.panel import Panel
import psutil
import time

def system_monitor():
    with Live(auto_refresh=False) as live:
        while True:
            # 获取系统数据
            cpu = psutil.cpu_percent(interval=1)
            mem = psutil.virtual_memory().percent
            disk = psutil.disk_usage('/').percent
            net = psutil.net_io_counters()
            
            # 构建动态仪表盘
            table = Table(title="系统监控", show_header=True)
            table.add_column("指标", style="cyan", justify="left")
            table.add_column("数值", style="magenta", justify="right")
            table.add_column("状态", style="yellow", justify="center")
            
            # 添加监控项
            table.add_row("CPU使用率", f"{cpu}%", "[green]正常[/]" if cpu < 80 else "[red]警告[/]")
            table.add_row("内存使用率", f"{mem}%", "[green]正常[/]" if mem < 70 else "[red]警告[/]")
            table.add_row("磁盘空间", f"{disk}%", "[green]正常[/]" if disk < 90 else "[red]警告[/]")
            table.add_row("网络流量", f"{net.bytes_sent/1024:.1f} KB/s ↔ {net.bytes_recv/1024:.1f} KB/s", "")
            
            # 创建带边框的面板
            panel = Panel.fit(
                table,
                title="实时系统监控",
                border_style="bright_magenta",
                padding=(1, 2)
            )
            
            live.update(panel, refresh=True)
            time.sleep(1)

system_monitor()